/** autor Konjkov.VV@gmail.com */

#include <string>
#include <iostream>

#include "Database.h"
#include "Sqlerr.h"

Database::Database(){
    SQLAllocEnv( &env );
    SQLAllocConnect( env, &dbc );
};

void Database::Connect(std::string server){
    SQLRETURN retcode = SQLConnect( dbc, (SQLCHAR*)server.c_str(), SQL_NTS, NULL, 0, NULL, 0 );
    if ( retcode == SQL_ERROR ) {
        std::cerr << __FILE__ << ":" << __LINE__;
        throw Sqlerr(env, dbc, SQL_NULL_HSTMT);
    }
    SQLSetConnectAttr( dbc, SQL_ATTR_AUTOCOMMIT, (void*)SQL_AUTOCOMMIT_ON, SQL_NTS );
//    SQLSetConnectAttr( dbc, SQL_ATTR_METADATA_ID, (void*)SQL_TRUE, SQL_NTS);
};

void Database::SetAttr(SQLINTEGER option, SQLPOINTER value){
    SQLRETURN retcode = SQLSetConnectAttr( dbc, option, value, SQL_NTS );
    if ( retcode == SQL_ERROR ) {
        std::cerr << __FILE__ << ":" << __LINE__;
        throw Sqlerr(env, dbc, SQL_NULL_HSTMT);
    }
};

void Database::Commit(){
    SQLRETURN retcode = SQLEndTran( SQL_HANDLE_DBC , dbc , SQL_COMMIT );
    if ( retcode == SQL_ERROR ) {
        std::cerr << __FILE__ << ":" << __LINE__;
        throw Sqlerr(env, dbc, SQL_NULL_HSTMT);
    }
};

void Database::Rollback(){
    SQLRETURN retcode = SQLEndTran( SQL_HANDLE_DBC , dbc , SQL_ROLLBACK );
    if ( retcode == SQL_ERROR ) {
        std::cerr << __FILE__ << ":" << __LINE__;
        throw Sqlerr(env, dbc, SQL_NULL_HSTMT);
    }
};

void Database::Disconnect(){
    SQLRETURN retcode = SQLDisconnect( dbc );
    if ( retcode == SQL_ERROR ) {
        std::cerr << __FILE__ << ":" << __LINE__;
        throw Sqlerr(env, dbc, SQL_NULL_HSTMT);
    }
};

Statement Database::AllocStatement(){
    return Statement( env, dbc );
};

Database::~Database(){
    SQLFreeConnect( dbc );
    SQLFreeEnv( env );
};
